package com.newgrand.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.newgrand.domain.dbo.UIPCommon;
import com.newgrand.mapper.*;
import com.newgrand.model.*;
import com.newgrand.utils.i8util.EntityConverter;
import com.newgrand.utils.i8util.I8Request;
import com.newgrand.utils.i8util.I8ResultUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: zhanglixin
 * @Data: 2023/7/9 15:35
 * @Description: TODO
 */
@Service
public class ContractService {

    @Autowired
    private I8Request i8Request;
    @Autowired
    private EntityConverter entityConverter;

    @Autowired
    private Pcm3CntTypeMapper pcm3CntTypeMapper;

    @Autowired
    private UIPCommonMapper uipCommonMapper;

    @Autowired
    private ProjectTableMapper projectTableMapper;

    @Autowired
    private FgOrglistMapper fgOrglistMapper;

    @Autowired
    private Fg3EnterpriseMapper fg3EnterpriseMapper;

    @Autowired
    private MsunitMapper msunitMapper;


    private final static String mstformDataStr = "{\"form\":{\"key\":\"PhId\",\"newRow\":{\"BillNo\":\"\",\"Title\":\"\",\"BillDt\":\"2023-07-09\",\"CntType\":\"3\",\"PhidPc\":\"490230629000005\",\"CntSumVatFc\":1130,\"SignDt\":\"\",\"PhidRecComp\":\"690220901000002\",\"SenEmp\":\"\",\"Stat\":\"new\",\"PhidSenComp\":\"336230327000002\",\"PhidSenEmp\":\"\",\"PhidSchComp\":\"\",\"PhidOcode\":\"146220711000002\",\"PhidDept\":\"\",\"PhidPm\":\"\",\"PhidCm\":\"\",\"StartDt\":\"\",\"EndDt\":\"\",\"InvoiceCmp\":\"336230327000002\",\"InvoiceSen\":\"690220901000002\",\"CntSumVat\":1130,\"Remarks\":\"\",\"PurchaseMode\":\"\",\"PhidCgPlan\":\"\",\"PrintCount\":\"\",\"BRPcNo\":\"LJ-202306-0070\",\"BillType\":\"7\",\"CntOrgSumFc\":1000,\"CntOrgSum\":1000,\"CntOrgTaxAmtFc\":130,\"CntOrgTaxAmt\":130,\"CntOrgSumVatFc\":1130,\"CntOrgSumVat\":1130,\"CntTaxAmt\":130,\"CntTaxAmtFc\":130,\"CntSumFc\":1000,\"CntSum\":1000,\"ChSumAmtVat\":\"\",\"ChSumAmtVatFc\":\"\",\"ChSumAmt\":\"\",\"ChSumAmtFc\":\"\",\"ChSumTaxamt\":\"\",\"ChSumTaxamtFc\":\"\",\"Creator\":\"146220711000003\",\"NgInsertDt\":\"2023-07-09\",\"ListFilterVal\":\"\",\"QueryField1Val\":\"\",\"QueryField2Val\":\"\",\"UIMultiConfigID\":\"\",\"Py\":\"HTMCCS\",\"PhId\":\"\",\"ChkFlg\":\"0\",\"PhidChkPsn\":\"\",\"DaFlg\":\"\",\"WfFlg\":\"\",\"NgRecordVer\":\"\",\"PhidSchemeId\":\"454230630000004\",\"ImpInfo\":\"\",\"PhidCheckupId\":\"\",\"PhidXyId\":\"\",\"PhidSourcemid\":\"\",\"ItemResource\":\"\",\"PhidKg\":\"\",\"CntTemplate\":\"\",\"PhIdEntOrgId1\":\"146220711000002\",\"PhIdEntOrgId2\":\"146220711000003\",\"PointId\":\"\",\"CurrType\":\"1\",\"PhidThdCmp\":\"\",\"ThdEmp\":\"\",\"ExchRate\":1,\"Zfbl\":1,\"PhidSeater\":\"\",\"PhidParentId\":\"\",\"PhidPe\":\"\",\"PhidWbs\":\"\",\"StampsControl\":\"\",\"PhidStampsitem\":\"\",\"RecordStat\":\"0\",\"RecordDt\":\"\",\"PhidYsfl\":\"12\",\"Iscb\":\"0\",\"PhidCountAge\":\"\",\"IsPayFix\":\"1\",\"PhidTask\":\"\",\"AsrFlg\":\"0\",\"ToSeat\":\"0\",\"StampsFlg\":\"0\",\"NeedRecord\":\"0\",\"IsFixPriceCon\":\"0\",\"IsAmtCon\":\"0\",\"IsCntChild\":\"0\",\"key\":\"\",\"user_sybw\":\"\",\"user_syfw\":\"\",\"user_fkbl\":\"\",\"user_zhtbh\":\"\",\"user_sghtfkbl\":\"\",\"user_fbfgxs\":\"\",\"user_htjgxs\":\"\",\"user_yjljzje\":\"\",\"user_glms\":\"\",\"user_qtmx\":\"\",\"user_tgcgptcg\":\"\",\"user_jlfs\":\"\"}}}";
    private final static String cntdgridDataStr = "[{\"row\":{\"PhId\":\"\",\"Lineid\":1,\"PPhId\":\"\",\"ItemNo\":\"202307090009\",\"ItemName\":\"大幅度发\",\"PhidBoq\":\"\",\"PhidBoq_EXName\":\"\",\"PhidBoqD\":\"\",\"PhidActid\":\"\",\"PhidActid_EXName\":\"\",\"Spec\":\"\",\"Unit\":\"336230327000002\",\"Unit_EXName\":\"平方米\",\"PhidItemId\":\"\",\"PhidItemId_EXName\":\"\",\"Qty\":100,\"Prc\":10,\"PrcVat\":11.3,\"PrcFc\":10,\"PrcVatFc\":11.3,\"Amt\":1000,\"AmtVat\":1130,\"AmtFc\":1000,\"AmtVatFc\":1130,\"TaxRate\":0.13,\"OriTaxRate\":0.13,\"TaxAmt\":130,\"TimeType\":\"\",\"PhidWbs\":\"\",\"PhidWbs_EXName\":\"\",\"PhidCbs\":\"\",\"PhidCbs_EXName\":\"\",\"PhidProjType\":\"\",\"PhidProjType_EXName\":\"\",\"Character\":\"\",\"Demand\":\"\",\"PhidZbCnt\":\"\",\"PhidZbCnt_EXName\":\"\",\"FzQty\":0,\"QtyOri\":100,\"PrcOri\":10,\"PrcOriVat\":11.3,\"PrcOriFc\":10,\"PrcOriVatFc\":11.3,\"OriAmtFc\":1000,\"OriAmtVatFc\":1130,\"OriAmt\":1000,\"OriAmtVat\":1130,\"PhidSourceMId\":\"\",\"PhidSourceId\":\"\",\"ItemResource\":\"freeadd\",\"Remarks\":\"\",\"NgRecordVer\":0,\"Creator\":\"\",\"Editor\":\"\",\"CurOrgId\":\"\",\"LevelId\":\"0\",\"PhidFbfw\":\"\",\"PhidFbfw_EXName\":\"\",\"PhidPc\":\"490230629000005\",\"OperFlg\":\"cnt\",\"PhidCntChg\":\"\",\"ImpInfo\":\"\",\"RestQty\":0,\"RestAmtVat\":0,\"RestAmtVatFc\":0,\"RestAmt\":0,\"RestAmtFc\":0,\"ControlQty\":0,\"ControlAmtVat\":0,\"ControlAmtVatFc\":0,\"ControlAmt\":0,\"ControlAmtFc\":0,\"AuxItems1\":\"\",\"AuxItems3\":\"\",\"AuxItems2\":\"\",\"PhidItemdata\":\"\",\"PhidResBs\":\"\",\"ResPropertys\":\"\",\"CurrType\":\"1\",\"ExchRate\":1,\"Days\":0,\"PhidPc_EXName\":\"景湾小区三期1、2、22、24栋工程\",\"PhidAssetType\":\"\",\"PhidYsfl\":\"\",\"PhidAssetType_EXName\":\"\",\"MustInputCol\":\"\",\"jcqd\":\"\",\"PhidAsset\":\"\",\"IsFarmProduce\":0,\"VendorPrc\":\"\",\"TotalSumLc\":0,\"TotalSumUnVatLc\":0,\"TotalSumTax\":0,\"TotalSumTaxLc\":0,\"MonthPrcFc\":0,\"MonthPrcVatFc\":0,\"MonthPrc\":0,\"MonthPrcVat\":0,\"OriMonthPrcFc\":0,\"OriMonthPrcVatFc\":0,\"OriMonthPrc\":0,\"OriMonthPrcVat\":0,\"CompStartDt\":0,\"OriCompStartDt\":0,\"Months\":0,\"OriMonths\":0,\"OriMonthsAmt\":0,\"OriMonthsAmtVat\":0,\"OriMonthsAmtFc\":0,\"OriMonthsAmtVatFc\":0,\"MonthsAmt\":0,\"MonthsAmtVat\":0,\"MonthsAmtFc\":0,\"MonthsAmtVatFc\":0,\"MonthsTaxAmt\":0,\"MonthsTaxAmtFc\":0,\"OriMonthsTaxAmtFc\":0,\"OriMonthsTaxAmt\":0,\"PhIdItemdataFsepid\":\"\",\"ItemSepType\":\"\",\"PhidNonmsunit\":\"\",\"PhidSubcM\":\"\",\"PhidSubcD\":\"\",\"FyType\":\"\",\"FySx\":\"\",\"KksCode\":\"\",\"ResMasterData\":\"\",\"ItemDataNo\":\"\",\"BoqCode\":\"\",\"Area\":0,\"UmConvAm\":0,\"NonMsunit\":\"\",\"Weight\":\"\",\"Vol\":\"\",\"CBSAmt\":0,\"CBSAmtVat\":0,\"CBSBalance\":0,\"CBSBalanceVat\":0,\"CBSQty\":0,\"CBSRestQty\":0,\"CBSCntSumAmt\":0,\"CBSCntTypeBalance\":0,\"IMPSourceTbl\":\"\",\"ListModelNo\":\"\",\"BoqLevelName\":\"\",\"ResOtherName\":\"\",\"CurrType_Name\":\"人民币\",\"ResourceName\":\"\",\"PhidFeeType\":\"\",\"PhidFeeType_EXName\":\"\",\"MBillType\":\"\",\"Cglx\":\"\",\"AssetProp\":\"\",\"AssetCode\":\"\",\"AssetName\":\"\",\"XYCntAmt\":0,\"TotalSumUnVat\":0,\"SumTaxrate\":0,\"RefQty\":0,\"RefAmtVatFc\":0,\"PlanPrc\":0,\"OriTaxAmt\":130,\"OriTaxAmtLc\":130,\"TaxAmtLc\":130,\"XyAmtLc\":0,\"XyAmtVatLc\":0,\"OriXyAmtVatLc\":0,\"OriXyAmtLc\":0,\"OriTotalSumUnvat\":0,\"OriSumTaxrate\":0,\"OriXySumTaxLc\":0,\"OriTotalSum\":0,\"XySumTaxLc\":0,\"OriDays\":0,\"PhidResBs_EXCode\":\"\",\"PhidResBs_EXName\":\"\",\"FyType_EXName\":\"\",\"FySx_EXName\":\"\",\"key\":null}}]";

    public I8ReturnModel save(String data){
        try {
            JSONObject dataJO = JSONObject.parseObject(data);
            String bill_no = dataJO.getString("合同编号");
            String title = dataJO.getString("合同名称");
            String cnt_code = dataJO.getString("合同分类");
            QueryWrapper<Pcm3CntType> pcm3CntTypeQueryWrapper = new QueryWrapper<>();
            pcm3CntTypeQueryWrapper.eq("cnt_code",cnt_code);
            List<Pcm3CntType> pcm3CntTypeList = pcm3CntTypeMapper.selectList(pcm3CntTypeQueryWrapper);
            String CntType = "";
            String cntmodel = "";
            String bustype = "";
            if(pcm3CntTypeList!=null&&pcm3CntTypeList.size()>0){
                Pcm3CntType pcm3CntType = pcm3CntTypeList.get(0);
                CntType = pcm3CntType.getPhid();
                cntmodel = pcm3CntType.getCntMode();
                bustype = "CON"+pcm3CntType.getCntMode();
            }else{
                return I8ResultUtil.error("合同分类:"+cnt_code+"未找到.");
            }

            JSONObject edataJO = dataJO.getJSONObject("e_data");
            String projectId = edataJO.getString("projectId");//项目id，来源项管
            String signingTime = edataJO.getString("signingTime");//签订时间，来源合同管理
            String projectContractCode = edataJO.getString("projectContractCode");//项目合同编号，来源项管
            String partyA = edataJO.getString("partyA");//发包方or需方id，来源勤科
            String partyB = edataJO.getString("partyB"); //分包方or供方id，来源勤科
            String projectSubordinateUnits = edataJO.getString("projectSubordinateUnits"); //项目所属单位id,来源勤科

            //乙方单位
            QueryWrapper<Fg3Enterprise> fg3EnterpriseQueryWrapper = new QueryWrapper<>();
            fg3EnterpriseQueryWrapper.eq("user_gysid",partyB);
            List<Fg3Enterprise> fg3EnterpriseList = fg3EnterpriseMapper.selectList(fg3EnterpriseQueryWrapper);
            String PhidRecComp = "0";
            String PhidSenComp = "0";
            if(fg3EnterpriseList!=null&&fg3EnterpriseList.size()>0){
                Fg3Enterprise fg3Enterprise = fg3EnterpriseList.get(0);
                PhidSenComp = fg3Enterprise.getPhid();
            }else{
                return I8ResultUtil.error("乙方单位:"+partyB+"未找到.");
            }

            //甲方单位
            QueryWrapper<FgOrglist> fgOrglistQueryWrapper = new QueryWrapper<>();
            fgOrglistQueryWrapper.eq("user_qkhr",partyA);
            List<FgOrglist> fgOrglistList = fgOrglistMapper.selectList(fgOrglistQueryWrapper);
            if(fgOrglistList!=null&&fgOrglistList.size()>0){
                FgOrglist fgOrglist = fgOrglistList.get(0);
                QueryWrapper<Fg3Enterprise> enterpriseQueryWrapper = new QueryWrapper<>();
                enterpriseQueryWrapper.eq("compno",fgOrglist.getOcode());
                List<Fg3Enterprise> enterpriseList = fg3EnterpriseMapper.selectList(enterpriseQueryWrapper);
                if(enterpriseList!=null&&enterpriseList.size()>0){
                    Fg3Enterprise fg3Enterprise = enterpriseList.get(0);
                    PhidRecComp = fg3Enterprise.getPhid();
                }else{
                    return I8ResultUtil.error("甲方单位:"+partyA+"未找到.");
                }
            }else{
                return I8ResultUtil.error("组织:"+partyA+"未找到.");
            }


            ProjectTable projectTable = projectTableMapper.selectById(projectId);
            String PhidPc = "0";
            String PhidOcode = "0";
            if(projectTable!=null){
                PhidPc = projectTable.getPhid();
                PhidOcode = projectTable.getCatPhid();
            }else{
                return I8ResultUtil.error("项目信息:"+projectId+"未找到.");
            }

            List<UIPCommon> uipCommonList = uipCommonMapper.getPhids("select phid from imp3_scheme where biztype=(select phid from metadata_bustree where code='"+bustype+"') and isuse='1'");
            String PhidSchemeId = "0";
            if(uipCommonList!=null&&uipCommonList.size()>0){
                UIPCommon uipCommon = uipCommonList.get(0);
                PhidSchemeId = uipCommon.getPhid();
            }else{
                return I8ResultUtil.error("imp方案未维护");
            }

            List<NameValuePair> urlParameters = new ArrayList<>();
            HashMap<String, Object> mainMap = new HashMap<String, Object>();
            mainMap.put("BillNo", bill_no);
            mainMap.put("Title", title);
            mainMap.put("BillDt",signingTime);
            mainMap.put("SignDt",signingTime);
            mainMap.put("CntType", CntType);
            mainMap.put("PhidPc", PhidPc);

            String user_sybw = dataJO.getString("承包使用部位");
            mainMap.put("user_sybw",user_sybw);
            String user_syfw = dataJO.getString("承包使用范围");
            mainMap.put("user_syfw",user_syfw);
            String user_fkbl = dataJO.getString("分包合同结算方式及付款比例");
            mainMap.put("user_fkbl",user_fkbl);
            String user_zhtbh = dataJO.getString("主合同编号");
            mainMap.put("user_zhtbh",user_zhtbh);
            String user_sghtfkbl = dataJO.getString("施工合同付款比例");
            mainMap.put("user_sghtfkbl",user_sghtfkbl);
            String user_fbfgxs = dataJO.getString("分包分供形式");
            mainMap.put("user_fbfgxs",user_fbfgxs);
            String user_htjgxs = dataJO.getString("合同价格形式");
            mainMap.put("user_htjgxs",user_htjgxs);
            String user_yjljzje = dataJO.getString("分包合计预计累计总金额");
            mainMap.put("user_yjljzje",user_yjljzje);
            String user_glms = dataJO.getString("经营方式");
            mainMap.put("user_glms",user_glms);
            String user_qtmx = dataJO.getString("其他明细");
            mainMap.put("user_qtmx",user_qtmx);
            String user_tgcgptcg = dataJO.getString("通过采购平台采购");
            mainMap.put("user_tgcgptcg",user_tgcgptcg);
            String user_jlfs = dataJO.getString("计量方式");
            mainMap.put("user_jlfs",user_jlfs);
            //甲方单位
            mainMap.put("PhidRecComp", PhidRecComp);
            mainMap.put("InvoiceSen", PhidRecComp);
            //乙方单位
            mainMap.put("PhidSenComp", PhidSenComp);
            mainMap.put("InvoiceCmp", PhidSenComp);
            mainMap.put("PhidOcode", PhidOcode);
            mainMap.put("PhIdEntOrgId1", PhidOcode);

            mainMap.put("PhidSchemeId", PhidSchemeId);

            List<Msunit> msunitList = msunitMapper.selectList(null);

            ArrayList<HashMap<String, Object>> detailList = new ArrayList<>();
            JSONArray items = dataJO.getJSONArray("formson_7053");
            int count = items.size();
            BigDecimal cntsum = new BigDecimal("0");
            for(int i=0;i<count;i++){
                JSONObject item = items.getJSONObject(i);
                String PrcVat = item.getString("单价含税明细");
                String AmtVat = item.getString("总价明细");//含税金额
                BigDecimal amtvat = new BigDecimal(AmtVat);
                cntsum = cntsum.add(amtvat);
                String Qty = item.getString("暂定工程量明细");
                String unit = item.getString("计量单位明细");
                double taxrate  = Double.parseDouble(item.getString("税率明细"))/100;//3.00

                BigDecimal TaxAmt =amtvat.multiply(new BigDecimal(taxrate)).setScale(2, RoundingMode.HALF_DOWN);//税额
                BigDecimal Amt = amtvat.subtract(TaxAmt);//不含税金额
                BigDecimal Prc = Amt.divide(new BigDecimal(Qty)).setScale(4,RoundingMode.HALF_DOWN);//不含税单价

                HashMap<String, Object> detailMap = new HashMap<String, Object>();
                detailMap.put("Lineid",i+1);
                detailMap.put("ItemNo",item.getString("序号"));
                detailMap.put("ItemName",item.getString("名称明细"));

                List<Msunit> msunits = msunitList.stream().filter(t -> unit.equals(t.getMsname())).collect(Collectors.toList());
                String Unit = "0";
                if(msunits!=null&&msunits.size()>0)
                {
                    Unit = msunits.get(0).getPhid();
                }
                detailMap.put("Unit",Unit);
                detailMap.put("Qty",Qty);
                detailMap.put("QtyOri",Qty);

                detailMap.put("Prc",Prc);
                detailMap.put("PrcFc",Prc);
                detailMap.put("PrcOri",Prc);
                detailMap.put("PrcOriFc",Prc);

                detailMap.put("PrcVat",PrcVat);
                detailMap.put("PrcVatFc",PrcVat);
                detailMap.put("PrcOriVat",PrcVat);
                detailMap.put("PrcOriVatFc",PrcVat);

                detailMap.put("Amt",Amt);
                detailMap.put("AmtFc",Amt);
                detailMap.put("OriAmtFc",Amt);
                detailMap.put("OriAmt",Amt);

                detailMap.put("AmtVat",AmtVat);
                detailMap.put("AmtVatFc",AmtVat);
                detailMap.put("OriAmtVatFc",AmtVat);
                detailMap.put("OriAmtVat",AmtVat);

                detailMap.put("TaxRate",taxrate);
                detailMap.put("OriTaxRate",taxrate);
                detailMap.put("PhidPc",PhidPc);

                detailMap.put("TaxAmt",TaxAmt);
                detailMap.put("OriTaxAmt",TaxAmt);
                detailMap.put("OriTaxAmtLc",TaxAmt);
                detailMap.put("TaxAmtLc",TaxAmt);
                detailList.add(detailMap);
            }

            mainMap.put("CntSumVatFc", cntsum);
            mainMap.put("CntSumVat", cntsum);
            mainMap.put("BillType", cntmodel);
            mainMap.put("CntOrgSumFc", cntsum);
            mainMap.put("CntOrgSum", cntsum);
            mainMap.put("CntOrgTaxAmtFc",cntsum);
            mainMap.put("CntOrgTaxAmt", cntsum);
            mainMap.put("CntOrgSumVatFc", cntsum);
            mainMap.put("CntOrgSumVat", cntsum);
            mainMap.put("CntTaxAmt", cntsum);
            mainMap.put("CntTaxAmtFc", cntsum);
            mainMap.put("CntSumFc", cntsum);
            mainMap.put("CntSum", cntsum);

            urlParameters.add(new BasicNameValuePair("cntmodel", cntmodel));
            urlParameters.add(new BasicNameValuePair("bustype", bustype));

            urlParameters.add(new BasicNameValuePair("mstformData", entityConverter.SetFieldForm(mstformDataStr, mainMap)));
            urlParameters.add(new BasicNameValuePair("cntdgridData", entityConverter.SetTableRow(cntdgridDataStr, detailList)));
            urlParameters.add(new BasicNameValuePair("cntfydgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            urlParameters.add(new BasicNameValuePair("cntLeveData", "{\"table\":{\"key\":\"PhId\"}}"));
            urlParameters.add(new BasicNameValuePair("cntitemparamgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            urlParameters.add(new BasicNameValuePair("cntdescparamgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            urlParameters.add(new BasicNameValuePair("cntptypeparamgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            urlParameters.add(new BasicNameValuePair("cntcollectgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            urlParameters.add(new BasicNameValuePair("saveGuid", ""));
            urlParameters.add(new BasicNameValuePair("imptaskid", ""));
            String i8rv = i8Request.PostFormSync("/PMS/PCM/CntM/Save", urlParameters);
            JSONObject i8rvJson = JSON.parseObject(i8rv);
            if (i8rvJson != null && i8rvJson.getString("Status").toLowerCase().equals("success")) {
                return I8ResultUtil.success("接收成功");
            } else {
                return I8ResultUtil.error("接收失败:"+i8rvJson.getString("Msg"));
            }

        }catch (Exception ex){
            return I8ResultUtil.error("接口异常:"+ex.getMessage());
        }
    }
}
